package com.ht.api.handler.auth;

import org.springframework.stereotype.Component;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.UserInfo;
import com.ht.api.constant.CacheConstants;
import com.ht.api.db.util.RedisUtil;
import com.ht.api.util.JwtUtils;
import com.ht.api.util.UserUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 鉴权：是否登陆
 * @author asq
 * @createTime 2024年12月21日 17:29:11
 */
@Component
public class CheckLogin implements ICheck {
	@Override
	public AjaxResult check(HttpServletRequest req, HttpServletResponse res) {
		// 检查前端header头中是否带有token数据
		String token = req.getHeader(JwtUtils.TOKEN_KEY);
		if (token == null || token.isEmpty()) {
			token = req.getParameter(JwtUtils.TOKEN_KEY);
		}
		if (token == null) {
			return faultLogin(res);
		}

		// 检查用户名
		String username = JwtUtils.getUsername(token);
		if (username == null) {
			return faultLogin(res);
		}

		// 从缓存获取登陆用户
		UserInfo info = UserUtil.getUserInfo(req);
		if (info == null) {
			return faultLogin(res);
		}

		boolean verify = JwtUtils.verify(token, info.getUuid());
		if (verify) {
			// 登陆有效期续期
			RedisUtil.expire(CacheConstants.KEY_USER + username, CacheConstants.EXPIRE_TOKEN);

			return AjaxResult.success();
		} else {
			return faultLogin(res);
		}
	}

	private AjaxResult faultLogin(HttpServletResponse res) {
		res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		return FAULT_LOGIN;
	}

}
